package com.chungkui.check.handler.impl;

import com.chungkui.check.configparser.bean.CheckConfig;
import com.chungkui.check.core.TrafficControlService;
import com.chungkui.check.core.bean.CheckResult;
import com.chungkui.check.handler.CheckHandler;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

/**
 * @Author: jason
 * @Date: 2019/12/30 16:51
 * @Version 1.0
 */

public class TrafficControlCheckHandler implements CheckHandler {
    @Autowired(required = false)
    TrafficControlService trafficControlService;
    private final Logger log = LoggerFactory.getLogger(TrafficControlCheckHandler.class);

    @Override
    public CheckResult check(CheckConfig checkConfig, Map<String, Object> params) {
        CheckConfig.TrafficControlConfig trafficControlConfig = checkConfig.getTrafficControlConfig();
        boolean result = true;
        CheckResult checkResult=new CheckResult(true);
        if (trafficControlConfig != null) {
            checkResult.setCode(trafficControlConfig.getCode());
            if (trafficControlService == null) {
                log.error("You need to provide an implementation of the interface 'TrafficControlService'.");
                checkResult.setIfPass(false);
                return checkResult;
            }
            if (StringUtils.isNotEmpty(trafficControlConfig.getDynamicParam())) {
                result = trafficControlService.dynamicCheck(trafficControlConfig.getKey(), MapUtils.getString(params, trafficControlConfig.getDynamicParam()));
            } else {
                result = trafficControlService.check(trafficControlConfig.getKey());
            }
        }
        if (result) {
            return CheckResult.success();
        } else {
            return CheckResult.fail(trafficControlConfig.getCode(), trafficControlConfig.getMsg());
        }
    }


    @Override
    public int sort() {
        return 3;
    }
}
